package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.RpListLvAdapter;
import com.ycsj.goldmedalnewconcept.bean.RgInfo;
import com.ycsj.goldmedalnewconcept.bean.RgInfo.RedPacketBean;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;

/**
 * 创建日期：2017/11/8  14:08
 * 描述:家长端--我的红包界面
 * 作者:张伟
 */

@SuppressLint("NewApi")
public class MyRedListActivity extends Activity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    //正常加载
    public static final int NORMAL = 0X110;

    //下拉刷新
    public static final int PULLTOREFRESH = 0X120;

    //返回
    private LinearLayout llBack;

    //加载
    private LinearLayout llLoading;

    //空数据
    private LinearLayout llEmpty;

    //刷新控件
    private PullToRefreshLayout ptrl;

    //列表控件
    private ListView lv;

    //列表数据
    private List<RgInfo.RedPacketBean> oldDatas;
    private RpListLvAdapter adapter;

	private String account;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myredlist);
        account = SPUtil.getString(this, "account", "");
        setBar();
        initView();
        //设置监听
        initListener();

        //初始化ListView
        initLv();

        //网络请求的方法
        http(NORMAL);
    }

    /**
     * 初始化控件
     */
    private void initView() {
        llBack = (LinearLayout) findViewById(R.id.ll_back);
        llLoading = (LinearLayout) findViewById(R.id.ll_loading);
        llEmpty = (LinearLayout) findViewById(R.id.ll_empty);
        ptrl = (PullToRefreshLayout) findViewById(R.id.refresh_view);
        lv = (ListView) findViewById(R.id.lv);
    }


    /**
     * 设置监听方法
     */
    private void initListener() {
        llBack.setOnClickListener(this);
        ptrl.setOnRefreshListener(this);
    }

    /**
     * 初始化ListView的方法
     */
    private void initLv() {
        oldDatas = new ArrayList<RedPacketBean>();
        adapter = new RpListLvAdapter(this, oldDatas, R.layout.item_lv_red_list);
    }


    /**
     * 网络请求的方法
     */
    private void http(final int method) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder();
        builder.add("type", "8");
        builder.add("c", account);
        builder.add("role", 1 + "");
        Request request = new Request.Builder()
                .url(Constant.SERVER_URL+"RedPacketMsg").post(builder.build())
                .build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //请求失败,主线程更新UI操作
                        if (llLoading != null) {
                            llLoading.setVisibility(View.GONE);
                        }
                        lv.setAdapter(adapter);
                        Toast.makeText(MyRedListActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Response arg0) throws IOException {
                try {
                    //请求成功
                    //获取服务器返回的json数据
                    String json = arg0.body().string();
                    if (!TextUtils.isEmpty(json)) {
                        RgInfo info = GsonUtil.jsonToBean(json, RgInfo.class);
                        //获取列表数据
                        final List<RgInfo.RedPacketBean> beanList = info.getRedPacket();
                        if (null != beanList && beanList.size() != 0) {
                        	
                        	Collections.reverse(beanList);//倒序处理
                            //证明有列表数据,更新主界面
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (method == NORMAL) {
                                        //正常请求
                                        if (llLoading != null) {
                                            llLoading.setVisibility(View.GONE);
                                        }
                                        oldDatas.addAll(beanList);
                                        lv.setAdapter(adapter);
                                    } else {
                                        //下拉刷新
                                        oldDatas.clear();
                                        oldDatas.addAll(beanList);
                                        ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //证明没有数据,显示空视图,隐藏加载框
                                    if (method == NORMAL) {
                                        //正常加载
                                        if (llLoading != null) {
                                            llLoading.setVisibility(View.GONE);
                                        }
                                        if (llEmpty != null) {
                                            llEmpty.setVisibility(View.VISIBLE);
                                        }
                                        lv.setAdapter(adapter);
                                    } else {
                                        //下拉刷新
                                        ptrl.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
                                    }
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
        }
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        http(PULLTOREFRESH);
    }


    /**
     * 设置沉浸状态栏的方法,需要在setContentView()之后调用
     */
    private void setBar() {
        //兼容5.0+，状态栏设置透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else
            //为了沉浸式状态栏 4.4以上才有
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
    }
}
